﻿

using NModbus;
using NModbus.Serial;
using System.Diagnostics;
using System;
using System.IO.Ports;

namespace DualPlaneFR4Paster.Common.Services
{
    public class StepMotorModbusService : IStepMotorModbusService
    {
        SerialPort serialPort = new SerialPort();
        IModbusMaster master;
        private object _lock1 = new object();
        public void Close()
        {
            try
            {
                master.Dispose();
                serialPort.Close();
                serialPort.Dispose();
            }
            catch { }
        }

        public bool Connect(string _portName)
        {
            try
            {
                if (this.serialPort.IsOpen)
                {
                    Debug.WriteLine($"步进串口{_portName}已打开");
                    return false;
                }
                else
                {
                    this.serialPort.PortName = _portName;
                    serialPort.BaudRate = 19200;
                    serialPort.DataBits = 8;
                    serialPort.Parity = Parity.None;
                    serialPort.StopBits = StopBits.One;
                    this.serialPort.Open();
                    this.serialPort.DiscardInBuffer();
                    this.serialPort.DiscardOutBuffer();
                    this.serialPort.WriteTimeout = 500;
                    this.serialPort.ReadTimeout = 500;
                    var factory = new ModbusFactory();
                    master = factory.CreateRtuMaster(serialPort);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return false;
        }

        public int GetMotorSpeed(int station, int address)
        {
            var data = master.ReadHoldingRegisters((byte)station, (ushort)address, 1);
            return data[0];
        }

        public void SetMotorSpeed(int station, int address, int value)
        {
            master.WriteSingleRegister((byte)station, (ushort)address, (ushort)value);
        }
    }
}
